home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / awksrc.zip / GAWK-D~1.14 / GAWK~6.INF (.txt) < prev    next >
GNU Info File  |  1993-10-03  |  48KB  |  943 lines

  1. This is Info file gawk.info, produced by Makeinfo-1.47 from the input
  2. file gawk.texi.
  3.    This file documents `awk', a program that you can use to select
  4. particular records in a file and perform operations upon them.
  5.    This is Edition 0.14 of `The GAWK Manual',
  6. for the 2.14 version of the GNU implementation
  7. of AWK.
  8.    Copyright (C) 1989, 1991, 1992 Free Software Foundation, Inc.
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided that
  14. the entire resulting derived work is distributed under the terms of a
  15. permission notice identical to this one.
  16.    Permission is granted to copy and distribute translations of this
  17. manual into another language, under the above conditions for modified
  18. versions, except that this permission notice may be stated in a
  19. translation approved by the Foundation.
  20. File: gawk.info,  Node: Break Statement,  Next: Continue Statement,  Prev: For Statement,  Up: Statements
  21. The `break' Statement
  22. =====================
  23.    The `break' statement jumps out of the innermost `for', `while', or
  24. `do'-`while' loop that encloses it.  The following example finds the
  25. smallest divisor of any integer, and also identifies prime numbers:
  26.      awk '# find smallest divisor of num
  27.           { num = $1
  28.             for (div = 2; div*div <= num; div++)
  29.               if (num % div == 0)
  30.                 break
  31.             if (num % div == 0)
  32.               printf "Smallest divisor of %d is %d\n", num, div
  33.             else
  34.               printf "%d is prime\n", num  }'
  35.    When the remainder is zero in the first `if' statement, `awk'
  36. immediately "breaks out" of the containing `for' loop.  This means that
  37. `awk' proceeds immediately to the statement following the loop and
  38. continues processing.  (This is very different from the `exit'
  39. statement which stops the entire `awk' program. *Note The `exit'
  40. Statement: Exit Statement.)
  41.    Here is another program equivalent to the previous one.  It
  42. illustrates how the CONDITION of a `for' or `while' could just as well
  43. be replaced with a `break' inside an `if':
  44.      awk '# find smallest divisor of num
  45.           { num = $1
  46.             for (div = 2; ; div++) {
  47.               if (num % div == 0) {
  48.                 printf "Smallest divisor of %d is %d\n", num, div
  49.                 break
  50.               }
  51.               if (div*div > num) {
  52.                 printf "%d is prime\n", num
  53.                 break
  54.               }
  55.             }
  56.      }'
  57. File: gawk.info,  Node: Continue Statement,  Next: Next Statement,  Prev: Break Statement,  Up: Statements
  58. The `continue' Statement
  59. ========================
  60.    The `continue' statement, like `break', is used only inside `for',
  61. `while', and `do'-`while' loops.  It skips over the rest of the loop
  62. body, causing the next cycle around the loop to begin immediately. 
  63. Contrast this with `break', which jumps out of the loop altogether. 
  64. Here is an example:
  65.      # print names that don't contain the string "ignore"
  66.      
  67.      # first, save the text of each line
  68.      { names[NR] = $0 }
  69.      
  70.      # print what we're interested in
  71.      END {
  72.         for (x in names) {
  73.             if (names[x] ~ /ignore/)
  74.                 continue
  75.             print names[x]
  76.         }
  77.      }
  78.    If one of the input records contains the string `ignore', this
  79. example skips the print statement for that record, and continues back to
  80. the first statement in the loop.
  81.    This is not a practical example of `continue', since it would be
  82. just as easy to write the loop like this:
  83.      for (x in names)
  84.        if (names[x] !~ /ignore/)
  85.          print names[x]
  86.    The `continue' statement in a `for' loop directs `awk' to skip the
  87. rest of the body of the loop, and resume execution with the
  88. increment-expression of the `for' statement.  The following program
  89. illustrates this fact:
  90.      awk 'BEGIN {
  91.           for (x = 0; x <= 20; x++) {
  92.               if (x == 5)
  93.                   continue
  94.               printf ("%d ", x)
  95.           }
  96.           print ""
  97.      }'
  98. This program prints all the numbers from 0 to 20, except for 5, for
  99. which the `printf' is skipped.  Since the increment `x++' is not
  100. skipped, `x' does not remain stuck at 5.  Contrast the `for' loop above
  101. with the `while' loop:
  102.      awk 'BEGIN {
  103.           x = 0
  104.           while (x <= 20) {
  105.               if (x == 5)
  106.                   continue
  107.               printf ("%d ", x)
  108.               x++
  109.           }
  110.           print ""
  111.      }'
  112. This program loops forever once `x' gets to 5.
  113.    As described above, the `continue' statement has no meaning when
  114. used outside the body of a loop.  However, although it was never
  115. documented, historical implementations of `awk' have treated the
  116. `continue' statement outside of a loop as if it were a `next' statement
  117. (*note The `next' Statement: Next Statement.). By default, `gawk'
  118. silently supports this usage.  However, if `-W posix' has been
  119. specified on the command line (*note Invoking `awk': Command Line.), it
  120. will be treated as an error, since the POSIX standard specifies that
  121. `continue' should only be used inside the body of a loop.
  122. File: gawk.info,  Node: Next Statement,  Next: Next File Statement,  Prev: Continue Statement,  Up: Statements
  123. The `next' Statement
  124. ====================
  125.    The `next' statement forces `awk' to immediately stop processing the
  126. current record and go on to the next record.  This means that no
  127. further rules are executed for the current record.  The rest of the
  128. current rule's action is not executed either.
  129.    Contrast this with the effect of the `getline' function (*note
  130. Explicit Input with `getline': Getline.).  That too causes `awk' to
  131. read the next record immediately, but it does not alter the flow of
  132. control in any way.  So the rest of the current action executes with a
  133. new input record.
  134.    At the highest level, `awk' program execution is a loop that reads
  135. an input record and then tests each rule's pattern against it.  If you
  136. think of this loop as a `for' statement whose body contains the rules,
  137. then the `next' statement is analogous to a `continue' statement: it
  138. skips to the end of the body of this implicit loop, and executes the
  139. increment (which reads another record).
  140.    For example, if your `awk' program works only on records with four
  141. fields, and you don't want it to fail when given bad input, you might
  142. use this rule near the beginning of the program:
  143.      NF != 4 {
  144.        printf("line %d skipped: doesn't have 4 fields", FNR) > "/dev/stderr"
  145.        next
  146.      }
  147. so that the following rules will not see the bad record.  The error
  148. message is redirected to the standard error output stream, as error
  149. messages should be.  *Note Standard I/O Streams: Special Files.
  150.    According to the POSIX standard, the behavior is undefined if the
  151. `next' statement is used in a `BEGIN' or `END' rule. `gawk' will treat
  152. it as a syntax error.
  153.    If the `next' statement causes the end of the input to be reached,
  154. then the code in the `END' rules, if any, will be executed. *Note
  155. `BEGIN' and `END' Special Patterns: BEGIN/END.
  156. File: gawk.info,  Node: Next File Statement,  Next: Exit Statement,  Prev: Next Statement,  Up: Statements
  157. The `next file' Statement
  158. =========================
  159.    The `next file' statement is similar to the `next' statement.
  160. However, instead of abandoning processing of the current record, the
  161. `next file' statement instructs `awk' to stop processing the current
  162. data file.
  163.    Upon execution of the `next file' statement, `FILENAME' is updated
  164. to the name of the next data file listed on the command line, `FNR' is
  165. reset to 1, and processing starts over with the first rule in the
  166. progam.  *Note Built-in Variables::.
  167.    If the `next file' statement causes the end of the input to be
  168. reached, then the code in the `END' rules, if any, will be executed.
  169. *Note `BEGIN' and `END' Special Patterns: BEGIN/END.
  170.    The `next file' statement is a `gawk' extension; it is not
  171. (currently) available in any other `awk' implementation.  You can
  172. simulate its behavior by creating a library file named `nextfile.awk',
  173. with the following contents.  (This sample program uses user-defined
  174. functions, a feature that has not been presented yet. *Note
  175. User-defined Functions: User-defined, for more information.)
  176.      # nextfile --- function to skip remaining records in current file
  177.      
  178.      # this should be read in before the "main" awk program
  179.      
  180.      function nextfile() { _abandon_ = FILENAME; next }
  181.      
  182.      _abandon_ == FILENAME && FNR > 1   { next }
  183.      _abandon_ == FILENAME && FNR == 1  { _abandon_ = "" }
  184.    The `nextfile' function simply sets a "private" variable(1) to the
  185. name of the current data file, and then retrieves the next record. 
  186. Since this file is read before the main `awk' program, the rules that
  187. follows the function definition will be executed before the rules in
  188. the main program.  The first rule continues to skip records as long as
  189. the name of the input file has not changed, and this is not the first
  190. record in the file.  This rule is sufficient most of the time.  But
  191. what if the *same* data file is named twice in a row on the command
  192. line? This rule would not process the data file the second time.  The
  193. second rule catches this case: If the data file name is what was being
  194. skipped, but `FNR' is 1, then this is the second time the file is being
  195. processed, and it should not be skipped.
  196.    The `next file' statement would be useful if you have many data
  197. files to process, and due to the nature of the data, you expect that you
  198. would not want to process every record in the file.  In order to move
  199. on to the next data file, you would have to continue scanning the
  200. unwanted records (as described above).  The `next file' statement
  201. accomplishes this much more efficiently.
  202.    ---------- Footnotes ----------
  203.    (1)  Since all variables in `awk' are global, this program uses the
  204. common practice of prefixing the variable name with an underscore.  In
  205. fact, it also suffixes the variable name with an underscore, as extra
  206. insurance against using a variable name that might be used in some
  207. other library file.
  208. File: gawk.info,  Node: Exit Statement,  Prev: Next File Statement,  Up: Statements
  209. The `exit' Statement
  210. ====================
  211.    The `exit' statement causes `awk' to immediately stop executing the
  212. current rule and to stop processing input; any remaining input is
  213. ignored.
  214.    If an `exit' statement is executed from a `BEGIN' rule the program
  215. stops processing everything immediately.  No input records are read. 
  216. However, if an `END' rule is present, it is executed (*note `BEGIN' and
  217. `END' Special Patterns: BEGIN/END.).
  218.    If `exit' is used as part of an `END' rule, it causes the program to
  219. stop immediately.
  220.    An `exit' statement that is part of an ordinary rule (that is, not
  221. part of a `BEGIN' or `END' rule) stops the execution of any further
  222. automatic rules, but the `END' rule is executed if there is one. If you
  223. do not want the `END' rule to do its job in this case, you can set a
  224. variable to nonzero before the `exit' statement, and check that
  225. variable in the `END' rule.
  226.    If an argument is supplied to `exit', its value is used as the exit
  227. status code for the `awk' process.  If no argument is supplied, `exit'
  228. returns status zero (success).
  229.    For example, let's say you've discovered an error condition you
  230. really don't know how to handle.  Conventionally, programs report this
  231. by exiting with a nonzero status.  Your `awk' program can do this using
  232. an `exit' statement with a nonzero argument.  Here's an example of this:
  233.      BEGIN {
  234.             if (("date" | getline date_now) < 0) {
  235.               print "Can't get system date" > "/dev/stderr"
  236.               exit 4
  237.             }
  238.      }
  239. File: gawk.info,  Node: Arrays,  Next: Built-in,  Prev: Statements,  Up: Top
  240. Arrays in `awk'
  241. ***************
  242.    An "array" is a table of values, called "elements".  The elements of
  243. an array are distinguished by their indices.  "Indices" may be either
  244. numbers or strings.  Each array has a name, which looks like a variable
  245. name, but must not be in use as a variable name in the same `awk'
  246. program.
  247. * Menu:
  248. * Array Intro::                 Introduction to Arrays
  249. * Reference to Elements::       How to examine one element of an array.
  250. * Assigning Elements::          How to change an element of an array.
  251. * Array Example::               Basic Example of an Array
  252. * Scanning an Array::           A variation of the `for' statement.
  253.                                 It loops through the indices of
  254.                                 an array's existing elements.
  255. * Delete::                      The `delete' statement removes
  256.                                 an element from an array.
  257. * Numeric Array Subscripts::    How to use numbers as subscripts in `awk'.
  258. * Multi-dimensional::           Emulating multi-dimensional arrays in `awk'.
  259. * Multi-scanning::              Scanning multi-dimensional arrays.
  260. File: gawk.info,  Node: Array Intro,  Next: Reference to Elements,  Prev: Arrays,  Up: Arrays
  261. Introduction to Arrays
  262. ======================
  263.    The `awk' language has one-dimensional "arrays" for storing groups
  264. of related strings or numbers.
  265.    Every `awk' array must have a name.  Array names have the same
  266. syntax as variable names; any valid variable name would also be a valid
  267. array name.  But you cannot use one name in both ways (as an array and
  268. as a variable) in one `awk' program.
  269.    Arrays in `awk' superficially resemble arrays in other programming
  270. languages; but there are fundamental differences.  In `awk', you don't
  271. need to specify the size of an array before you start to use it.
  272. Additionally, any number or string in `awk' may be used as an array
  273. index.
  274.    In most other languages, you have to "declare" an array and specify
  275. how many elements or components it contains.  In such languages, the
  276. declaration causes a contiguous block of memory to be allocated for that
  277. many elements.  An index in the array must be a positive integer; for
  278. example, the index 0 specifies the first element in the array, which is
  279. actually stored at the beginning of the block of memory.  Index 1
  280. specifies the second element, which is stored in memory right after the
  281. first element, and so on.  It is impossible to add more elements to the
  282. array, because it has room for only as many elements as you declared.
  283.    A contiguous array of four elements might look like this,
  284. conceptually, if the element values are `8', `"foo"', `""' and `30':
  285.      +---------+---------+--------+---------+
  286.      |    8    |  "foo"  |   ""   |    30   |    value
  287.      +---------+---------+--------+---------+
  288.           0         1         2         3        index
  289. Only the values are stored; the indices are implicit from the order of
  290. the values.  `8' is the value at index 0, because `8' appears in the
  291. position with 0 elements before it.
  292.    Arrays in `awk' are different: they are "associative".  This means
  293. that each array is a collection of pairs: an index, and its
  294. corresponding array element value:
  295.      Element 4     Value 30
  296.      Element 2     Value "foo"
  297.      Element 1     Value 8
  298.      Element 3     Value ""
  299. We have shown the pairs in jumbled order because their order is
  300. irrelevant.
  301.    One advantage of an associative array is that new pairs can be added
  302. at any time.  For example, suppose we add to the above array a tenth
  303. element whose value is `"number ten"'.  The result is this:
  304.      Element 10    Value "number ten"
  305.      Element 4     Value 30
  306.      Element 2     Value "foo"
  307.      Element 1     Value 8
  308.      Element 3     Value ""
  309. Now the array is "sparse" (i.e., some indices are missing): it has
  310. elements 1--4 and 10, but doesn't have elements 5, 6, 7, 8, or 9.
  311.    Another consequence of associative arrays is that the indices don't
  312. have to be positive integers.  Any number, or even a string, can be an
  313. index.  For example, here is an array which translates words from
  314. English into French:
  315.      Element "dog" Value "chien"
  316.      Element "cat" Value "chat"
  317.      Element "one" Value "un"
  318.      Element 1     Value "un"
  319. Here we decided to translate the number 1 in both spelled-out and
  320. numeric form--thus illustrating that a single array can have both
  321. numbers and strings as indices.
  322.    When `awk' creates an array for you, e.g., with the `split' built-in
  323. function, that array's indices are consecutive integers starting at 1.
  324. (*Note Built-in Functions for String Manipulation: String Functions.)
  325. File: gawk.info,  Node: Reference to Elements,  Next: Assigning Elements,  Prev: Array Intro,  Up: Arrays
  326. Referring to an Array Element
  327. =============================
  328.    The principal way of using an array is to refer to one of its
  329. elements. An array reference is an expression which looks like this:
  330.      ARRAY[INDEX]
  331. Here, ARRAY is the name of an array.  The expression INDEX is the index
  332. of the element of the array that you want.
  333.    The value of the array reference is the current value of that array
  334. element.  For example, `foo[4.3]' is an expression for the element of
  335. array `foo' at index 4.3.
  336.    If you refer to an array element that has no recorded value, the
  337. value of the reference is `""', the null string.  This includes elements
  338. to which you have not assigned any value, and elements that have been
  339. deleted (*note The `delete' Statement: Delete.).  Such a reference
  340. automatically creates that array element, with the null string as its
  341. value. (In some cases, this is unfortunate, because it might waste
  342. memory inside `awk').
  343.    You can find out if an element exists in an array at a certain index
  344. with the expression:
  345.      INDEX in ARRAY
  346. This expression tests whether or not the particular index exists,
  347. without the side effect of creating that element if it is not present.
  348. The expression has the value 1 (true) if `ARRAY[INDEX]' exists, and 0
  349. (false) if it does not exist.
  350.    For example, to test whether the array `frequencies' contains the
  351. index `"2"', you could write this statement:
  352.      if ("2" in frequencies) print "Subscript \"2\" is present."
  353.    Note that this is *not* a test of whether or not the array
  354. `frequencies' contains an element whose *value* is `"2"'. (There is no
  355. way to do that except to scan all the elements.)  Also, this *does not*
  356. create `frequencies["2"]', while the following (incorrect) alternative
  357. would do so:
  358.      if (frequencies["2"] != "") print "Subscript \"2\" is present."
  359. File: gawk.info,  Node: Assigning Elements,  Next: Array Example,  Prev: Reference to Elements,  Up: Arrays
  360. Assigning Array Elements
  361. ========================
  362.    Array elements are lvalues: they can be assigned values just like
  363. `awk' variables:
  364.      ARRAY[SUBSCRIPT] = VALUE
  365. Here ARRAY is the name of your array.  The expression SUBSCRIPT is the
  366. index of the element of the array that you want to assign a value.  The
  367. expression VALUE is the value you are assigning to that element of the
  368. array.
  369. File: gawk.info,  Node: Array Example,  Next: Scanning an Array,  Prev: Assigning Elements,  Up: Arrays
  370. Basic Example of an Array
  371. =========================
  372.    The following program takes a list of lines, each beginning with a
  373. line number, and prints them out in order of line number.  The line
  374. numbers are not in order, however, when they are first read:  they are
  375. scrambled.  This program sorts the lines by making an array using the
  376. line numbers as subscripts.  It then prints out the lines in sorted
  377. order of their numbers. It is a very simple program, and gets confused
  378. if it encounters repeated numbers, gaps, or lines that don't begin with
  379. a number.
  380.      {
  381.        if ($1 > max)
  382.          max = $1
  383.        arr[$1] = $0
  384.      }
  385.      
  386.      END {
  387.        for (x = 1; x <= max; x++)
  388.          print arr[x]
  389.      }
  390.    The first rule keeps track of the largest line number seen so far;
  391. it also stores each line into the array `arr', at an index that is the
  392. line's number.
  393.    The second rule runs after all the input has been read, to print out
  394. all the lines.
  395.    When this program is run with the following input:
  396.      5  I am the Five man
  397.      2  Who are you?  The new number two!
  398.      4  . . . And four on the floor
  399.      1  Who is number one?
  400.      3  I three you.
  401. its output is this:
  402.      1  Who is number one?
  403.      2  Who are you?  The new number two!
  404.      3  I three you.
  405.      4  . . . And four on the floor
  406.      5  I am the Five man
  407.    If a line number is repeated, the last line with a given number
  408. overrides the others.
  409.    Gaps in the line numbers can be handled with an easy improvement to
  410. the program's `END' rule:
  411.      END {
  412.        for (x = 1; x <= max; x++)
  413.          if (x in arr)
  414.            print arr[x]
  415.      }
  416. File: gawk.info,  Node: Scanning an Array,  Next: Delete,  Prev: Array Example,  Up: Arrays
  417. Scanning all Elements of an Array
  418. =================================
  419.    In programs that use arrays, often you need a loop that executes
  420. once for each element of an array.  In other languages, where arrays are
  421. contiguous and indices are limited to positive integers, this is easy:
  422. the largest index is one less than the length of the array, and you can
  423. find all the valid indices by counting from zero up to that value.  This
  424. technique won't do the job in `awk', since any number or string may be
  425. an array index.  So `awk' has a special kind of `for' statement for
  426. scanning an array:
  427.      for (VAR in ARRAY)
  428.        BODY
  429. This loop executes BODY once for each different value that your program
  430. has previously used as an index in ARRAY, with the variable VAR set to
  431. that index.
  432.    Here is a program that uses this form of the `for' statement.  The
  433. first rule scans the input records and notes which words appear (at
  434. least once) in the input, by storing a 1 into the array `used' with the
  435. word as index.  The second rule scans the elements of `used' to find
  436. all the distinct words that appear in the input.  It prints each word
  437. that is more than 10 characters long, and also prints the number of
  438. such words.  *Note Built-in Functions: Built-in, for more information
  439. on the built-in function `length'.
  440.      # Record a 1 for each word that is used at least once.
  441.      {
  442.        for (i = 1; i <= NF; i++)
  443.          used[$i] = 1
  444.      }
  445.      
  446.      # Find number of distinct words more than 10 characters long.
  447.      END {
  448.        for (x in used)
  449.          if (length(x) > 10) {
  450.            ++num_long_words
  451.            print x
  452.        }
  453.        print num_long_words, "words longer than 10 characters"
  454.      }
  455. *Note Sample Program::, for a more detailed example of this type.
  456.    The order in which elements of the array are accessed by this
  457. statement is determined by the internal arrangement of the array
  458. elements within `awk' and cannot be controlled or changed.  This can
  459. lead to problems if new elements are added to ARRAY by statements in
  460. BODY; you cannot predict whether or not the `for' loop will reach them.
  461.  Similarly, changing VAR inside the loop can produce strange results. 
  462. It is best to avoid such things.
  463. File: gawk.info,  Node: Delete,  Next: Numeric Array Subscripts,  Prev: Scanning an Array,  Up: Arrays
  464. The `delete' Statement
  465. ======================
  466.    You can remove an individual element of an array using the `delete'
  467. statement:
  468.      delete ARRAY[INDEX]
  469.    You can not refer to an array element after it has been deleted; it
  470. is as if you had never referred to it and had never given it any value.
  471.  You can no longer obtain any value the element once had.
  472.    Here is an example of deleting elements in an array:
  473.      for (i in frequencies)
  474.        delete frequencies[i]
  475. This example removes all the elements from the array `frequencies'.
  476.    If you delete an element, a subsequent `for' statement to scan the
  477. array will not report that element, and the `in' operator to check for
  478. the presence of that element will return 0:
  479.      delete foo[4]
  480.      if (4 in foo)
  481.        print "This will never be printed"
  482.    It is not an error to delete an element which does not exist.
  483. File: gawk.info,  Node: Numeric Array Subscripts,  Next: Multi-dimensional,  Prev: Delete,  Up: Arrays
  484. Using Numbers to Subscript Arrays
  485. =================================
  486.    An important aspect of arrays to remember is that array subscripts
  487. are *always* strings.  If you use a numeric value as a subscript, it
  488. will be converted to a string value before it is used for subscripting
  489. (*note Conversion of Strings and Numbers: Conversion.).
  490.    This means that the value of the `CONVFMT' can potentially affect
  491. how your program accesses elements of an array.  For example:
  492.      a = b = 12.153
  493.      data[a] = 1
  494.      CONVFMT = "%2.2f"
  495.      if (b in data)
  496.          printf "%s is in data", b
  497.      else
  498.          printf "%s is not in data", b
  499. should print `12.15 is not in data'.  The first statement gives both
  500. `a' and `b' the same numeric value.  Assigning to `data[a]' first gives
  501. `a' the string value `"12.153"' (using the default conversion value of
  502. `CONVFMT', `"%.6g"'), and then assigns 1 to `data["12.153"]'.  The
  503. program then changes the value of `CONVFMT'.  The test `(b in data)'
  504. forces `b' to be converted to a string, this time `"12.15"', since the
  505. value of `CONVFMT' only allows two significant digits.  This test fails,
  506. since `"12.15"' is a different string from `"12.153"'.
  507.    According to the rules for conversions (*note Conversion of Strings
  508. and Numbers: Conversion.), integer values are always converted to
  509. strings as integers, no matter what the value of `CONVFMT' may happen
  510. to be.  So the usual case of
  511.      for (i = 1; i <= maxsub; i++)
  512.          do something with array[i]
  513. will work, no matter what the value of `CONVFMT'.
  514.    Like many things in `awk', the majority of the time things work as
  515. you would expect them to work.  But it is useful to have a precise
  516. knowledge of the actual rules, since sometimes they can have a subtle
  517. effect on your programs.
  518. File: gawk.info,  Node: Multi-dimensional,  Next: Multi-scanning,  Prev: Numeric Array Subscripts,  Up: Arrays
  519. Multi-dimensional Arrays
  520. ========================
  521.    A multi-dimensional array is an array in which an element is
  522. identified by a sequence of indices, not a single index.  For example, a
  523. two-dimensional array requires two indices.  The usual way (in most
  524. languages, including `awk') to refer to an element of a two-dimensional
  525. array named `grid' is with `grid[X,Y]'.
  526.    Multi-dimensional arrays are supported in `awk' through
  527. concatenation of indices into one string.  What happens is that `awk'
  528. converts the indices into strings (*note Conversion of Strings and
  529. Numbers: Conversion.) and concatenates them together, with a separator
  530. between them.  This creates a single string that describes the values
  531. of the separate indices.  The combined string is used as a single index
  532. into an ordinary, one-dimensional array.  The separator used is the
  533. value of the built-in variable `SUBSEP'.
  534.    For example, suppose we evaluate the expression `foo[5,12]="value"'
  535. when the value of `SUBSEP' is `"@"'.  The numbers 5 and 12 are
  536. converted to strings and concatenated with an `@' between them,
  537. yielding `"5@12"'; thus, the array element `foo["5@12"]' is set to
  538. `"value"'.
  539.    Once the element's value is stored, `awk' has no record of whether
  540. it was stored with a single index or a sequence of indices.  The two
  541. expressions `foo[5,12]' and `foo[5 SUBSEP 12]' always have the same
  542. value.
  543.    The default value of `SUBSEP' is the string `"\034"', which contains
  544. a nonprinting character that is unlikely to appear in an `awk' program
  545. or in the input data.
  546.    The usefulness of choosing an unlikely character comes from the fact
  547. that index values that contain a string matching `SUBSEP' lead to
  548. combined strings that are ambiguous.  Suppose that `SUBSEP' were `"@"';
  549. then `foo["a@b", "c"]' and `foo["a", "b@c"]' would be indistinguishable
  550. because both would actually be stored as `foo["a@b@c"]'.  Because
  551. `SUBSEP' is `"\034"', such confusion can arise only when an index
  552. contains the character with ASCII code 034, which is a rare event.
  553.    You can test whether a particular index-sequence exists in a
  554. "multi-dimensional" array with the same operator `in' used for single
  555. dimensional arrays.  Instead of a single index as the left-hand operand,
  556. write the whole sequence of indices, separated by commas, in
  557. parentheses:
  558.      (SUBSCRIPT1, SUBSCRIPT2, ...) in ARRAY
  559.    The following example treats its input as a two-dimensional array of
  560. fields; it rotates this array 90 degrees clockwise and prints the
  561. result.  It assumes that all lines have the same number of elements.
  562.      awk '{
  563.           if (max_nf < NF)
  564.                max_nf = NF
  565.           max_nr = NR
  566.           for (x = 1; x <= NF; x++)
  567.                vector[x, NR] = $x
  568.      }
  569.      
  570.      END {
  571.           for (x = 1; x <= max_nf; x++) {
  572.                for (y = max_nr; y >= 1; --y)
  573.                     printf("%s ", vector[x, y])
  574.                printf("\n")
  575.           }
  576.      }'
  577. When given the input:
  578.      1 2 3 4 5 6
  579.      2 3 4 5 6 1
  580.      3 4 5 6 1 2
  581.      4 5 6 1 2 3
  582. it produces:
  583.      4 3 2 1
  584.      5 4 3 2
  585.      6 5 4 3
  586.      1 6 5 4
  587.      2 1 6 5
  588.      3 2 1 6
  589. File: gawk.info,  Node: Multi-scanning,  Prev: Multi-dimensional,  Up: Arrays
  590. Scanning Multi-dimensional Arrays
  591. =================================
  592.    There is no special `for' statement for scanning a
  593. "multi-dimensional" array; there cannot be one, because in truth there
  594. are no multi-dimensional arrays or elements; there is only a
  595. multi-dimensional *way of accessing* an array.
  596.    However, if your program has an array that is always accessed as
  597. multi-dimensional, you can get the effect of scanning it by combining
  598. the scanning `for' statement (*note Scanning all Elements of an Array:
  599. Scanning an Array.) with the `split' built-in function (*note Built-in
  600. Functions for String Manipulation: String Functions.). It works like
  601. this:
  602.      for (combined in ARRAY) {
  603.        split(combined, separate, SUBSEP)
  604.        ...
  605.      }
  606. This finds each concatenated, combined index in the array, and splits it
  607. into the individual indices by breaking it apart where the value of
  608. `SUBSEP' appears.  The split-out indices become the elements of the
  609. array `separate'.
  610.    Thus, suppose you have previously stored in `ARRAY[1, "foo"]'; then
  611. an element with index `"1\034foo"' exists in ARRAY.  (Recall that the
  612. default value of `SUBSEP' contains the character with code 034.) 
  613. Sooner or later the `for' statement will find that index and do an
  614. iteration with `combined' set to `"1\034foo"'.  Then the `split'
  615. function is called as follows:
  616.      split("1\034foo", separate, "\034")
  617. The result of this is to set `separate[1]' to 1 and `separate[2]' to
  618. `"foo"'.  Presto, the original sequence of separate indices has been
  619. recovered.
  620. File: gawk.info,  Node: Built-in,  Next: User-defined,  Prev: Arrays,  Up: Top
  621. Built-in Functions
  622. ******************
  623.    "Built-in" functions are functions that are always available for
  624. your `awk' program to call.  This chapter defines all the built-in
  625. functions in `awk'; some of them are mentioned in other sections, but
  626. they are summarized here for your convenience.  (You can also define
  627. new functions yourself.  *Note User-defined Functions: User-defined.)
  628. * Menu:
  629. * Calling Built-in::            How to call built-in functions.
  630. * Numeric Functions::           Functions that work with numbers,
  631.                                 including `int', `sin' and `rand'.
  632. * String Functions::            Functions for string manipulation,
  633.                                 such as `split', `match', and `sprintf'.
  634. * I/O Functions::               Functions for files and shell commands.
  635. * Time Functions::              Functions for dealing with time stamps.
  636. File: gawk.info,  Node: Calling Built-in,  Next: Numeric Functions,  Prev: Built-in,  Up: Built-in
  637. Calling Built-in Functions
  638. ==========================
  639.    To call a built-in function, write the name of the function followed
  640. by arguments in parentheses.  For example, `atan2(y + z, 1)' is a call
  641. to the function `atan2', with two arguments.
  642.    Whitespace is ignored between the built-in function name and the
  643. open-parenthesis, but we recommend that you avoid using whitespace
  644. there.  User-defined functions do not permit whitespace in this way, and
  645. you will find it easier to avoid mistakes by following a simple
  646. convention which always works: no whitespace after a function name.
  647.    Each built-in function accepts a certain number of arguments.  In
  648. most cases, any extra arguments given to built-in functions are
  649. ignored.  The defaults for omitted arguments vary from function to
  650. function and are described under the individual functions.
  651.    When a function is called, expressions that create the function's
  652. actual parameters are evaluated completely before the function call is
  653. performed. For example, in the code fragment:
  654.      i = 4
  655.      j = sqrt(i++)
  656. the variable `i' is set to 5 before `sqrt' is called with a value of 4
  657. for its actual parameter.
  658. File: gawk.info,  Node: Numeric Functions,  Next: String Functions,  Prev: Calling Built-in,  Up: Built-in
  659. Numeric Built-in Functions
  660. ==========================
  661.    Here is a full list of built-in functions that work with numbers:
  662. `int(X)'
  663.      This gives you the integer part of X, truncated toward 0.  This
  664.      produces the nearest integer to X, located between X and 0.
  665.      For example, `int(3)' is 3, `int(3.9)' is 3, `int(-3.9)' is -3,
  666.      and `int(-3)' is -3 as well.
  667. `sqrt(X)'
  668.      This gives you the positive square root of X.  It reports an error
  669.      if X is negative.  Thus, `sqrt(4)' is 2.
  670. `exp(X)'
  671.      This gives you the exponential of X, or reports an error if X is
  672.      out of range.  The range of values X can have depends on your
  673.      machine's floating point representation.
  674. `log(X)'
  675.      This gives you the natural logarithm of X, if X is positive;
  676.      otherwise, it reports an error.
  677. `sin(X)'
  678.      This gives you the sine of X, with X in radians.
  679. `cos(X)'
  680.      This gives you the cosine of X, with X in radians.
  681. `atan2(Y, X)'
  682.      This gives you the arctangent of `Y / X' in radians.
  683. `rand()'
  684.      This gives you a random number.  The values of `rand' are
  685.      uniformly-distributed between 0 and 1.  The value is never 0 and
  686.      never 1.
  687.      Often you want random integers instead.  Here is a user-defined
  688.      function you can use to obtain a random nonnegative integer less
  689.      than N:
  690.           function randint(n) {
  691.                return int(n * rand())
  692.           }
  693.      The multiplication produces a random real number greater than 0
  694.      and less than N.  We then make it an integer (using `int') between
  695.      0 and `N - 1'.
  696.      Here is an example where a similar function is used to produce
  697.      random integers between 1 and N.  Note that this program will
  698.      print a new random number for each input record.
  699.           awk '
  700.           # Function to roll a simulated die.
  701.           function roll(n) { return 1 + int(rand() * n) }
  702.           
  703.           # Roll 3 six-sided dice and print total number of points.
  704.           {
  705.                 printf("%d points\n", roll(6)+roll(6)+roll(6))
  706.           }'
  707.      *Note:* `rand' starts generating numbers from the same point, or
  708.      "seed", each time you run `awk'.  This means that a program will
  709.      produce the same results each time you run it. The numbers are
  710.      random within one `awk' run, but predictable from run to run. 
  711.      This is convenient for debugging, but if you want a program to do
  712.      different things each time it is used, you must change the seed to
  713.      a value that will be different in each run.  To do this, use
  714.      `srand'.
  715. `srand(X)'
  716.      The function `srand' sets the starting point, or "seed", for
  717.      generating random numbers to the value X.
  718.      Each seed value leads to a particular sequence of "random" numbers.
  719.      Thus, if you set the seed to the same value a second time, you
  720.      will get the same sequence of "random" numbers again.
  721.      If you omit the argument X, as in `srand()', then the current date
  722.      and time of day are used for a seed.  This is the way to get random
  723.      numbers that are truly unpredictable.
  724.      The return value of `srand' is the previous seed.  This makes it
  725.      easy to keep track of the seeds for use in consistently reproducing
  726.      sequences of random numbers.
  727. File: gawk.info,  Node: String Functions,  Next: I/O Functions,  Prev: Numeric Functions,  Up: Built-in
  728. Built-in Functions for String Manipulation
  729. ==========================================
  730.    The functions in this section look at or change the text of one or
  731. more strings.
  732. `index(IN, FIND)'
  733.      This searches the string IN for the first occurrence of the string
  734.      FIND, and returns the position in characters where that occurrence
  735.      begins in the string IN.  For example:
  736.           awk 'BEGIN { print index("peanut", "an") }'
  737.      prints `3'.  If FIND is not found, `index' returns 0. (Remember
  738.      that string indices in `awk' start at 1.)
  739. `length(STRING)'
  740.      This gives you the number of characters in STRING.  If STRING is a
  741.      number, the length of the digit string representing that number is
  742.      returned.  For example, `length("abcde")' is 5.  By contrast,
  743.      `length(15 * 35)' works out to 3.  How?  Well, 15 * 35 = 525, and
  744.      525 is then converted to the string `"525"', which has three
  745.      characters.
  746.      If no argument is supplied, `length' returns the length of `$0'.
  747.      In older versions of `awk', you could call the `length' function
  748.      without any parentheses.  Doing so is marked as "deprecated" in the
  749.      POSIX standard.  This means that while you can do this in your
  750.      programs, it is a feature that can eventually be removed from a
  751.      future version of the standard.  Therefore, for maximal
  752.      portability of your `awk' programs you should always supply the
  753.      parentheses.
  754. `match(STRING, REGEXP)'
  755.      The `match' function searches the string, STRING, for the longest,
  756.      leftmost substring matched by the regular expression, REGEXP.  It
  757.      returns the character position, or "index", of where that
  758.      substring begins (1, if it starts at the beginning of STRING).  If
  759.      no match if found, it returns 0.
  760.      The `match' function sets the built-in variable `RSTART' to the
  761.      index.  It also sets the built-in variable `RLENGTH' to the length
  762.      in characters of the matched substring.  If no match is found,
  763.      `RSTART' is set to 0, and `RLENGTH' to -1.
  764.      For example:
  765.           awk '{
  766.                  if ($1 == "FIND")
  767.                    regex = $2
  768.                  else {
  769.                    where = match($0, regex)
  770.                    if (where)
  771.                      print "Match of", regex, "found at", where, "in", $0
  772.                  }
  773.           }'
  774.      This program looks for lines that match the regular expression
  775.      stored in the variable `regex'.  This regular expression can be
  776.      changed.  If the first word on a line is `FIND', `regex' is
  777.      changed to be the second word on that line.  Therefore, given:
  778.           FIND fo*bar
  779.           My program was a foobar
  780.           But none of it would doobar
  781.           FIND Melvin
  782.           JF+KM
  783.           This line is property of The Reality Engineering Co.
  784.           This file created by Melvin.
  785.      `awk' prints:
  786.           Match of fo*bar found at 18 in My program was a foobar
  787.           Match of Melvin found at 26 in This file created by Melvin.
  788. `split(STRING, ARRAY, FIELDSEP)'
  789.      This divides STRING into pieces separated by FIELDSEP, and stores
  790.      the pieces in ARRAY.  The first piece is stored in `ARRAY[1]', the
  791.      second piece in `ARRAY[2]', and so forth.  The string value of the
  792.      third argument, FIELDSEP, is a regexp describing where to split
  793.      STRING (much as `FS' can be a regexp describing where to split
  794.      input records).  If the FIELDSEP is omitted, the value of `FS' is
  795.      used. `split' returns the number of elements created.
  796.      The `split' function, then, splits strings into pieces in a manner
  797.      similar to the way input lines are split into fields.  For example:
  798.           split("auto-da-fe", a, "-")
  799.      splits the string `auto-da-fe' into three fields using `-' as the
  800.      separator.  It sets the contents of the array `a' as follows:
  801.           a[1] = "auto"
  802.           a[2] = "da"
  803.           a[3] = "fe"
  804.      The value returned by this call to `split' is 3.
  805.      As with input field-splitting, when the value of FIELDSEP is `"
  806.      "', leading and trailing whitespace is ignored, and the elements
  807.      are separated by runs of whitespace.
  808. `sprintf(FORMAT, EXPRESSION1,...)'
  809.      This returns (without printing) the string that `printf' would
  810.      have printed out with the same arguments (*note Using `printf'
  811.      Statements for Fancier Printing: Printf.). For example:
  812.           sprintf("pi = %.2f (approx.)", 22/7)
  813.      returns the string `"pi = 3.14 (approx.)"'.
  814. `sub(REGEXP, REPLACEMENT, TARGET)'
  815.      The `sub' function alters the value of TARGET. It searches this
  816.      value, which should be a string, for the leftmost substring
  817.      matched by the regular expression, REGEXP, extending this match as
  818.      far as possible.  Then the entire string is changed by replacing
  819.      the matched text with REPLACEMENT. The modified string becomes the
  820.      new value of TARGET.
  821.      This function is peculiar because TARGET is not simply used to
  822.      compute a value, and not just any expression will do: it must be a
  823.      variable, field or array reference, so that `sub' can store a
  824.      modified value there.  If this argument is omitted, then the
  825.      default is to use and alter `$0'.
  826.      For example:
  827.           str = "water, water, everywhere"
  828.           sub(/at/, "ith", str)
  829.      sets `str' to `"wither, water, everywhere"', by replacing the
  830.      leftmost, longest occurrence of `at' with `ith'.
  831.      The `sub' function returns the number of substitutions made (either
  832.      one or zero).
  833.      If the special character `&' appears in REPLACEMENT, it stands for
  834.      the precise substring that was matched by REGEXP.  (If the regexp
  835.      can match more than one string, then this precise substring may
  836.      vary.)  For example:
  837.           awk '{ sub(/candidate/, "& and his wife"); print }'
  838.      changes the first occurrence of `candidate' to `candidate and his
  839.      wife' on each input line.
  840.      Here is another example:
  841.           awk 'BEGIN {
  842.                   str = "daabaaa"
  843.                   sub(/a*/, "c&c", str)
  844.                   print str
  845.           }'
  846.      prints `dcaacbaaa'.  This show how `&' can represent a non-constant
  847.      string, and also illustrates the "leftmost, longest" rule.
  848.      The effect of this special character (`&') can be turned off by
  849.      putting a backslash before it in the string.  As usual, to insert
  850.      one backslash in the string, you must write two backslashes. 
  851.      Therefore, write `\\&' in a string constant to include a literal
  852.      `&' in the replacement. For example, here is how to replace the
  853.      first `|' on each line with an `&':
  854.           awk '{ sub(/\|/, "\\&"); print }'
  855.      *Note:* as mentioned above, the third argument to `sub' must be an
  856.      lvalue.  Some versions of `awk' allow the third argument to be an
  857.      expression which is not an lvalue.  In such a case, `sub' would
  858.      still search for the pattern and return 0 or 1, but the result of
  859.      the substitution (if any) would be thrown away because there is no
  860.      place to put it.  Such versions of `awk' accept expressions like
  861.      this:
  862.           sub(/USA/, "United States", "the USA and Canada")
  863.      But that is considered erroneous in `gawk'.
  864. `gsub(REGEXP, REPLACEMENT, TARGET)'
  865.      This is similar to the `sub' function, except `gsub' replaces
  866.      *all* of the longest, leftmost, *nonoverlapping* matching
  867.      substrings it can find.  The `g' in `gsub' stands for "global,"
  868.      which means replace everywhere.  For example:
  869.           awk '{ gsub(/Britain/, "United Kingdom"); print }'
  870.      replaces all occurrences of the string `Britain' with `United
  871.      Kingdom' for all input records.
  872.      The `gsub' function returns the number of substitutions made.  If
  873.      the variable to be searched and altered, TARGET, is omitted, then
  874.      the entire input record, `$0', is used.
  875.      As in `sub', the characters `&' and `\' are special, and the third
  876.      argument must be an lvalue.
  877. `substr(STRING, START, LENGTH)'
  878.      This returns a LENGTH-character-long substring of STRING, starting
  879.      at character number START.  The first character of a string is
  880.      character number one.  For example, `substr("washington", 5, 3)'
  881.      returns `"ing"'.
  882.      If LENGTH is not present, this function returns the whole suffix of
  883.      STRING that begins at character number START.  For example,
  884.      `substr("washington", 5)' returns `"ington"'.  This is also the
  885.      case if LENGTH is greater than the number of characters remaining
  886.      in the string, counting from character number START.
  887. `tolower(STRING)'
  888.      This returns a copy of STRING, with each upper-case character in
  889.      the string replaced with its corresponding lower-case character.
  890.      Nonalphabetic characters are left unchanged.  For example,
  891.      `tolower("MiXeD cAsE 123")' returns `"mixed case 123"'.
  892. `toupper(STRING)'
  893.      This returns a copy of STRING, with each lower-case character in
  894.      the string replaced with its corresponding upper-case character.
  895.      Nonalphabetic characters are left unchanged.  For example,
  896.      `toupper("MiXeD cAsE 123")' returns `"MIXED CASE 123"'.
  897. File: gawk.info,  Node: I/O Functions,  Next: Time Functions,  Prev: String Functions,  Up: Built-in
  898. Built-in Functions for Input/Output
  899. ===================================
  900. `close(FILENAME)'
  901.      Close the file FILENAME, for input or output.  The argument may
  902.      alternatively be a shell command that was used for redirecting to
  903.      or from a pipe; then the pipe is closed.
  904.      *Note Closing Input Files and Pipes: Close Input, regarding closing
  905.      input files and pipes.  *Note Closing Output Files and Pipes:
  906.      Close Output, regarding closing output files and pipes.
  907. `system(COMMAND)'
  908.      The system function allows the user to execute operating system
  909.      commands and then return to the `awk' program.  The `system'
  910.      function executes the command given by the string COMMAND.  It
  911.      returns, as its value, the status returned by the command that was
  912.      executed.
  913.      For example, if the following fragment of code is put in your `awk'
  914.      program:
  915.           END {
  916.                system("mail -s 'awk run done' operator < /dev/null")
  917.           }
  918.      the system operator will be sent mail when the `awk' program
  919.      finishes processing input and begins its end-of-input processing.
  920.      Note that much the same result can be obtained by redirecting
  921.      `print' or `printf' into a pipe.  However, if your `awk' program
  922.      is interactive, `system' is useful for cranking up large
  923.      self-contained programs, such as a shell or an editor.
  924.      Some operating systems cannot implement the `system' function.
  925.      `system' causes a fatal error if it is not supported.
  926. Controlling Output Buffering with `system'
  927. ------------------------------------------
  928.    Many utility programs will "buffer" their output; they save
  929. information to be written to a disk file or terminal in memory, until
  930. there is enough to be written in one operation.  This is often more
  931. efficient than writing every little bit of information as soon as it is
  932. ready.  However, sometimes it is necessary to force a program to
  933. "flush" its buffers; that is, write the information to its destination,
  934. even if a buffer is not full. You can do this from your `awk' program
  935. by calling `system' with a null string as its argument:
  936.      system("")   # flush output
  937. `gawk' treats this use of the `system' function as a special case, and
  938. is smart enough not to run a shell (or other command interpreter) with
  939. the empty command.  Therefore, with `gawk', this idiom is not only
  940. useful, it is efficient.  While this idiom should work with other `awk'
  941. implementations, it will not necessarily avoid starting an unnecessary
  942. shell.
  943.